package com.liuzeyuan.controller;

import java.util.HashMap;
import java.util.Map;

public class MapHelper<K, V> {
    private final Map<K, V> map;

    private MapHelper(Class<? extends Map<K, V>> cls) {
        try {
            map = cls.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
            throw new IllegalArgumentException(e);
        }
    }

    private MapHelper() {
        map = new HashMap<>();
    }

    public static <K, V> MapHelper<K, V> create() {
        return new MapHelper<>();
    }

    public static <K, V> MapHelper<K, V> create(Class<? extends Map<K, V>> cls) {
        return new MapHelper<>(cls);
    }

    public static Map<String, Object> map(Object... params) {
        if (params.length % 2 != 0) {
            throw new IllegalArgumentException();
        }
        Map<String, Object> result = new HashMap<>(params.length / 2);
        for (int i = 0; i < params.length / 2; i++) {
            String key = (String) params[i * 2];
            Object val = params[i * 2 + 1];
            result.put(key, val);
        }
        return result;
    }

    public MapHelper<K, V> put(K key, V value) {
        map.put(key, value);
        return this;
    }

    public MapHelper<K, V> putAll(Map<? extends K, ? extends V> m) {
        map.putAll(m);
        return this;
    }

    public Map<K, V> map() {
        return map;
    }
}
